<?php

namespace App\Repository\Repositories;

use App\Repository\Repositories\Interfaces\UserInvoiceRepository;
use App\Repository\Models\UserInvoice;

/**
 * Class UserInvoiceRepositoryEloquent.
 *
 * @package namespace App\Repository\Repositories;
 */
class UserInvoiceRepositoryEloquent extends BaseRepository implements UserInvoiceRepository
{
    /**
     * 搜索
     * @var array
     */
    protected $fieldSearchable = [
        'invoice_type'
    ];

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return UserInvoice::class;
    }

    public function setDefault($id)
    {
        $this->applyCriteria();
        $this->applyScope();

        \DB::beginTransaction();
        try {
            $this->model->update(['is_default' => 0]);
            $this->model->where('id', $id)->update(['is_default' => 1]);
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return false;
        }

        return true;
    }
    /*
     * 检测是否可继续添加发票
     * */
    public function checkInvoice(){

        $this->applyCriteria();
        $this->applyScope();
        try {
            // 查询 用户已增加的发票信息
            $person = $this->model->where('invoice_message', '1')->count();
            $companyNormal = $this->model->where(['invoice_message' => '2', 'invoice_type' => 1])->count();
            $companyProfessional = $this->model->where(['invoice_message' => '2', 'invoice_type' => 2])->count();

            $userInvoices['person'] = $person > 0 ? true : false;
            $userInvoices['companyNormal'] = $companyNormal > 0 ? true : false;
            $userInvoices['companyProfessional'] = $companyProfessional > 0 ? true : false;
            // 都不可创建
            if ($person > 0 && $companyNormal > 0 && $companyProfessional > 0) {
                $userInvoices['all'] = true;
            } else {
                $userInvoices['all'] = false;
            }
        }catch (\Exception $e){
            // 返回错误信息，排错
            return $e->getMessage();
        }
        return $userInvoices;
    }

}
